﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Security.Claims;
using ZhongKeSite.Common;
using ZhongKeSite.Common.Helper;
using ZhongKeSite.Service;
using ZhongKeSite.Web.Models;

namespace ZhongKeSite.Web.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class AccountController : BaseController
    {
        private ISysService sysService;
        IViewService viewService;
        public AccountController(ISysService _sysService
                               , IViewService _viewService)
        {
            sysService = _sysService;
            viewService = _viewService;
        }

        #region 首页
        /// <summary>
        /// 后台首页
        /// </summary>
        /// <returns></returns>
        [RoleAuthorize("Home")]
        public ActionResult Index()
        {
            try
            {
                return View();
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return Content(CommonConst.SystemErrorMessage);
            }
        }
        #endregion

        #region 登录，登出处理逻辑
        /// <summary>
        /// 登录页
        /// </summary>
        /// <returns></returns>
        public ActionResult Login(string ReturnUrl = "")
        {
            ViewBag.ReturnUrl = ReturnUrl;
            return View();
        }
        /// <summary>
        /// 获取登录验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSecurityCode()
        {
            try
            {
                string securityCode = ImageHelper.CreateRandomCode(4);
                byte[] buf = ImageHelper.CreateValidateGraphic(securityCode);
                string cookie = EncryptionHelper.TDES(EncryptionHelper.CType.encrypt, securityCode, AppSettings.VerifyCodeSecret);
                HttpContext.AddCookie(AppSettings.LoginVerifyCookieName, cookie, AppSettings.CookieExpire);
                return File(buf, "image/Jpeg");
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return Content(CommonConst.SystemErrorMessage);
            }
        }

        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(string username, string password, string vercode, string returnUrl = "")
        {
            try
            {
                var response = sysService.SignIn(HttpContext, username, password, vercode);
                if (response.success)
                {
                    var cuser = response.data;
                    string ip = HttpContext.GetIP();
                    var userInfo = new ClaimsPrincipal(
                             new ClaimsIdentity(new[]
                             {
                                new Claim(CommonConst.Login,cuser.Login),
                                new Claim(CommonConst.UserID,cuser.UserID),
                                new Claim(CommonConst.RoleId,cuser.RoleId),
                                new Claim(CommonConst.UserName,cuser.UserName),
                                new Claim(CommonConst. LoginCount,cuser.LoginCount.ToString()),
                                new Claim(CommonConst.LastLoginDate,cuser.LastLoginDate.ToString(CommonConst.LongDateFormat)),
                                new Claim(CommonConst.LoginIP,ip)
                             }, CommonConst.AdminAuthenticationScheme)
                        );

                    HttpContext.SignInAsync(CommonConst.AdminAuthenticationScheme, userInfo, new AuthenticationProperties
                    {
                        ExpiresUtc = DateTime.UtcNow.AddSeconds(AppSettings.CookieExpire),// 有效时间
                        IsPersistent = true,
                        AllowRefresh = false
                    });
                    string url = string.IsNullOrWhiteSpace(returnUrl) ? "/Admin/Account/Index" : returnUrl;

                    return Json(new { success = response.success, msg = response.msg, url = url });
                }
                else
                {
                    return Json(new { success = response.success, msg = response.msg });
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return Json(new { success = false, msg = "登录信息不正确，请检查" });
            }
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [RoleAuthorize("Home")]
        public ActionResult Logout()
        {
            try
            {
                //登出成功
                HttpContext.SignOutAsync(CommonConst.AdminAuthenticationScheme);
                if (Request.IsAjaxRequest())
                {
                    return Json(new { success = true, msg = "登出成功", url = Url.Action("Login", "Account") });
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            return RedirectToAction("Login", "Account");
        }

        /// <summary>
        /// 无权限提示页
        /// </summary>
        /// <returns></returns>
        public ActionResult Permission()
        {
            return View();
        }
        /// <summary>
        /// 错误提示页
        /// </summary>
        /// <returns></returns>
        public ActionResult Error()
        {
            return View();
        }
        #endregion
    }
}